/**
 * @Title: MainProjectCreateLogic.java
 * @Package cn.com.gome.generator.logic
 * @Description: 主项目创建
 * @author chenmin-ds
 * @date 2017年5月26日 下午2:49:05
 * @company cn.com.gome
 * @version V1.0
 */


package cn.com.gome.generator.logic;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.com.gome.framework.dao.entity.TblChildProjectInfo;
import cn.com.gome.framework.dao.entity.TblProjectBasicInfo;

import com.gomeplus.frame.exception.LogicsException;
import com.gomeplus.frame.logic.ILogics;
import com.gomeplus.frame.logic.ResultEnum;

/**
 * @author chenmin-ds
 * @ClassName: MainProjectCreateLogic
 * @Description: 主项目创建
 * @date 2017年5月26日 下午2:49:05
 */
@Service
public class ChildProjectBaseCreateLogic implements ILogics<Map<String, Object>> {

    private Logger logger = LoggerFactory.getLogger("ChildProjectBaseCreateLogic");

    @Override
    public ResultEnum exec(Map<String, Object> map) throws LogicsException {
        try {
            TblChildProjectInfo childProjectInfo = (TblChildProjectInfo) map.get("childProjectInfo");
            TblProjectBasicInfo projectBasicInfo = (TblProjectBasicInfo) map.get("projectBasicInfo");

            String pachagesPath = projectBasicInfo.getPackages().replace(".", "//");

            String projectPath = projectBasicInfo.getProjectPath().trim();
            if (!projectPath.endsWith("//")) {
                projectPath += "//";
                projectBasicInfo.setProjectPath(projectPath);
            }
            // 主项目创建--项目英文名---设置子项目路径
            projectPath += projectBasicInfo.getProjectEng() + "//";
            projectPath += projectBasicInfo.getProjectEng() + "-" + childProjectInfo.getChildProjectEng();
            childProjectInfo.setProjectPath(projectPath);

            File file = new File(projectPath);
            if (!file.exists()) {
                file.mkdir();
            }

            // 创建resources
            file = new File(projectPath + "//src//main//resources");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//java");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//test//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//" + childProjectInfo.getChildProjectEng());
            if (!file.exists()) {
                file.mkdirs();
            }

            projectPath += "//pom.xml";
            file = new File(projectPath);
            if (!file.exists()) {
                file.createNewFile();
            }

            // 拼装pom文件--字符串
            StringBuffer sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            sb.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
            sb.append("	xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n");
            sb.append("	<modelVersion>4.0.0</modelVersion>\n");
            sb.append("	<parent>\n");
            sb.append("		<groupId>" + projectBasicInfo.getPackages() + "</groupId>\n");
            sb.append("		<artifactId>" + projectBasicInfo.getProjectEng() + "</artifactId>\n");
            sb.append("		<version>0.0.1-SNAPSHOT</version>\n");
            sb.append("	</parent>\n");
            sb.append("	<groupId>" + projectBasicInfo.getPackages() + "</groupId>\n");
            sb.append("	<artifactId>" + projectBasicInfo.getProjectEng() + "-" + childProjectInfo.getChildProjectEng() + "</artifactId>\n");
            sb.append("	<version>0.0.1-SNAPSHOT</version>\n");
            sb.append("	<packaging>" + childProjectInfo.getPackageType() + "</packaging>\n");
            sb.append("	<name>" + projectBasicInfo.getProjectEng() + "-" + childProjectInfo.getChildProjectEng() + "</name>\n");
            sb.append("	<url>http://maven.apache.org</url>\n");
            sb.append("	<properties>");
            sb.append("		<profiles.dir>src/main/resources/props</profiles.dir>\n");
            sb.append("	</properties>\n");
            sb.append("	<dependencies>\n");
            sb.append(childProjectInfo.getBasicJar());

            if ("020".equals(childProjectInfo.getProjectType())) {
                sb.append("		<dependency>\n");
                sb.append("			<groupId>com.gome</groupId>\n");
                sb.append("			<artifactId>sso-common</artifactId>\n");
                sb.append("			<version>1.0.20140815UAT</version>\n");
                sb.append("			<exclusions>\n");
                sb.append("				<exclusion>\n");
                sb.append("					<groupId>javax.servlet</groupId>\n");
                sb.append("					<artifactId>servlet-api</artifactId>\n");
                sb.append("				</exclusion>\n");
                sb.append("				<exclusion>\n");
                sb.append("					<groupId>org.springframework</groupId>\n");
                sb.append("					<artifactId>*</artifactId>\n");
                sb.append("				</exclusion>\n");
                sb.append("			</exclusions>\n");
                sb.append("		</dependency>\n");
                sb.append("		<dependency>\n");
                sb.append("			<groupId>com.gome</groupId>\n");
                sb.append("			<artifactId>memberCore-utils</artifactId>\n");
                sb.append("			<version>1.0.20140909sit</version>\n");
                sb.append("			<exclusions>\n");
                sb.append("				<exclusion>\n");
                sb.append("					<groupId>javax.servlet</groupId>\n");
                sb.append("					<artifactId>servlet-api</artifactId>\n");
                sb.append("				</exclusion>\n");
                sb.append("				<exclusion>\n");
                sb.append("					<groupId>org.springframework</groupId>\n");
                sb.append("					<artifactId>*</artifactId>\n");
                sb.append("				</exclusion>\n");
                sb.append("			</exclusions>\n");
                sb.append("		</dependency>\n");
                sb.append("		<dependency>\n");
                sb.append("			<groupId>commons-codec</groupId>\n");
                sb.append("			<artifactId>commons-codec</artifactId>\n");
                sb.append("			<version>1.7</version>\n");
                sb.append("		</dependency>\n");
            }

            sb.append("	</dependencies>\n");

            if ("pom".equals(childProjectInfo.getPackageType())) {
                sb.append("	<modules></modules>\n");
            } else {
                sb.append("	<build>\n");
                if ("war".equals(childProjectInfo.getPackageType())) {
                    sb.append("		<finalName>" + projectBasicInfo.getProjectEng() + "-" + childProjectInfo.getChildProjectEng() + "</finalName>\n");
                }
                if (StringUtils.isNotEmpty(childProjectInfo.getConfigFileName())) {
                    sb.append("		<filters>\n");
                    if (childProjectInfo.getChildProjectEng().contains("dao") || childProjectInfo.getConfigFileName().contains("jdbc")) {
                        sb.append("<!-- 注意：dao层，不过滤jdbc配置文件  如果需要过滤其他文件，自己添加配置 -->\n");
                    } else {
                        sb.append("			<filter>${profiles.dir}\\${env}\\" + childProjectInfo.getConfigFileName() + "</filter>\n");
                    }
                    sb.append("		</filters>\n");
                }
                sb.append("		<resources>\n");
                sb.append("			<resource>\n");
                sb.append("				<directory>src/main/resources</directory>\n");
                sb.append("				<filtering>true</filtering>\n");
                sb.append("			</resource>\n");
                sb.append("		</resources>\n");
                sb.append("	</build>\n");


                if (StringUtils.isNotEmpty(childProjectInfo.getVersionConfig())) {
                    sb.append("	<profiles>\n");
                    sb.append(childProjectInfo.getVersionConfig());
                    sb.append("	</profiles>\n");
                } else {
                    sb.append("<profiles>\n");
                    sb.append("	<profile>\n");
                    sb.append("		<id>dev</id>\n");
                    sb.append("		<properties>\n");
                    sb.append("			<env>dev</env>\n");
                    sb.append("		</properties>\n");
                    sb.append("	</profile>\n");
                    sb.append("	<profile>\n");
                    sb.append("		<id>uat</id>\n");
                    sb.append("		<activation>\n");
                    sb.append("			<activeByDefault>true</activeByDefault>\n");
                    sb.append("		</activation>\n");
                    sb.append("		<properties>\n");
                    sb.append("			<env>uat</env>\n");
                    sb.append("		</properties>\n");
                    sb.append("	</profile>\n");
                    sb.append("	<profile>\n");
                    sb.append("		<id>pre</id>\n");
                    sb.append("		<properties>\n");
                    sb.append("			<env>pre</env>\n");
                    sb.append("		</properties>\n");
                    sb.append("	</profile>\n");
                    sb.append("	<profile>\n");
                    sb.append("		<id>live</id>\n");
                    sb.append("		<properties>\n");
                    sb.append("			<env>live</env>\n");
                    sb.append("		</properties>\n");
                    sb.append("	</profile>\n");
                    sb.append("	<profile>\n");
                    sb.append("		<id>drill</id>\n");
                    sb.append("		<properties>\n");
                    sb.append("			<env>live</env>\n");
                    sb.append("		</properties>\n");
                    sb.append("	</profile>\n");
                    sb.append("</profiles>\n");
                }
            }

            sb.append("</project>");
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(projectPath), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();
            editPomXml(projectBasicInfo.getProjectPath(), projectBasicInfo.getProjectEng(), childProjectInfo.getChildProjectEng());
            return ResultEnum.OK;
        } catch (Exception e) {
            logger.error("创建子项目异常：", e);
        }
        return ResultEnum.PART_CASE_01;
    }

    /**
     * 创建子项目时，修改主项目的pom文件
     * @param projectPath
     * @param projectEng
     * @param CHILD_PROJECT_ENG
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public void editPomXml(String projectPath, String projectEng, String CHILD_PROJECT_ENG) throws IOException {
        projectPath += projectEng + "//pom.xml";
        File file = new File(projectPath);
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(file);
            Element elementR = doc.getRootElement();
            Element element = elementR.element("modules");
            boolean t = true;
            if (element != null && element.elements().size() > 0) {
                List list1 = element.elements();
                Iterator iterator = list1.iterator();
                while (iterator.hasNext()) {
                    Element elem = (Element) iterator.next();
                    if ((projectEng + "-" + CHILD_PROJECT_ENG).equals(elem.getText())) {
                        t = false;
                    }
                }
            }
            if (t) {
                Element date = element.addElement("module");
                date.addText(projectEng + "-" + CHILD_PROJECT_ENG);
                FileWriter newFile = new FileWriter(new File(projectPath));
                XMLWriter newWriter = new XMLWriter(newFile);
                newWriter.write(doc);
                newWriter.close();
            }
        } catch (DocumentException e) {
            logger.error("修改主pom文件异常：", e);
        }
    }
}
